package com.neusoft.neuiotms.dcom.converter.change;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.neusoft.bizcore.web.dto.AbstractConverter;
import com.neusoft.neuiotms.dcom.dto.change.ChangeCiRelationDTO;
import com.neusoft.neuiotms.dcom.model.change.ChangeCiRelation;
import com.neusoft.neuiotms.dcom.repository.change.ChangeCiRelationRepository;

@Component
public class ChangeCiRelationConverter extends AbstractConverter<ChangeCiRelation, ChangeCiRelationDTO> {

    @Autowired
    private ChangeCiRelationRepository changeCiRelationRepository;

    @Override
    public ChangeCiRelation toModel(final ChangeCiRelationDTO dto) {
        ChangeCiRelation model;
        if (dto.isNew()) {
            model = new ChangeCiRelation();
        } else {
            model = this.changeCiRelationRepository.getOne(dto.getId());
        }
        model.setDescription(dto.getDesc());
        model.setSourceInstance(dto.getSrc());
        model.setSrouceInstanceDesc(dto.getSrcDesc());
        model.setTargetInstance(dto.getDest());
        model.setTargetInstanceDesc(dto.getDestDesc());
        model.setRelation(dto.getRela());
        model.setRelationDesc(dto.getRelaDesc());
        model.setRelationId(dto.getRelationId());
        model.setAttrs(dto.getAttrs().toJSONString());
        model.setDeleteFlag(dto.getDeleteFlag());
        model.setDescriptionChange(dto.getDescChange());
        if (dto.getAttrsChange() != null) {
            model.setAttrsChange(dto.getAttrsChange().toJSONString());
        } else {
            model.setAttrsChange(null);
        }
        model.setAddFlag(dto.getAddFlag());
        model.setUpdateTime(new Date());
        model.setTaskId(dto.getTaskId());
        return model;
    }

    @Override
    public ChangeCiRelationDTO toDTO(final ChangeCiRelation model, final boolean forListView) {
        final ChangeCiRelationDTO dto = new ChangeCiRelationDTO();
        dto.setId(model.getId());
        dto.setDesc(model.getDescription());
        dto.setSrc(model.getSourceInstance());
        dto.setSrcDesc(model.getSrouceInstanceDesc());
        dto.setDest(model.getTargetInstance());
        dto.setDestDesc(model.getTargetInstanceDesc());
        dto.setRela(model.getRelation());
        dto.setRelaDesc(model.getRelationDesc());
        dto.setRelationId(model.getRelationId());
        dto.setDeleteFlag(model.getDeleteFlag());
        dto.setAddFlag(model.getAddFlag());
        dto.setAttrs(JSON.parseObject(model.getAttrs()));
        dto.setDescChange(model.getDescriptionChange());
        dto.setAttrsChange(JSON.parseObject(model.getAttrsChange()));
        dto.setCreateTime(model.getCreateTime());
        dto.setUpdateTime(model.getUpdateTime());
        dto.setTaskId(model.getTaskId());

        return dto;
    }

}
